package com.mes.cloud.util;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;

/**
 *
 * Created by 18060132 on 2019-03-21.
 */
public class RegistBean {
    /**
     * 动态注册bean
     */
    public static void registBean(Class<?> beanClass){
        /**
         * 将applicationContext转换为ConfigurableApplicationContext
         */
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContextUtil.getApplicationContext();
        /**
         * 获取bean工厂并转换为DefaultListableBeanFactory
         */
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        /**
         * 通过BeanDefinitionBuilder创建bean定义
         */
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass.getClass());
        /**
         * 注册bean
         */
        defaultListableBeanFactory.registerBeanDefinition(beanClass.getName(), beanDefinitionBuilder.getRawBeanDefinition());
    }

}
